extends Spatial

onready var rigidbody_collection = $Tom_fragments
onready var pos3d = $Position3D.global_transform.origin

func _ready():
	rigidbody_collection.visible  = false
	

func create_rigids():
	if rigidbody_collection.visible:
		return
	for mesh in rigidbody_collection.get_children():
		if mesh is MeshInstance:
			var mesh_global_origin = mesh.global_transform.origin
			rigidbody_collection.remove_child(mesh)
			var rigid = RigidBody.new()
			mesh.global_transform.origin = Vector3.ZERO
			rigid.add_child(mesh)
			rigid.global_transform.origin = mesh_global_origin
			var collision = CollisionShape.new()
			rigid.add_child(collision)
			collision.make_convex_from_brothers()
			rigidbody_collection.add_child(rigid)
			
	rigidbody_collection.visible = true
	
	
	
func explode():
	for rigid in rigidbody_collection.get_children():
		if rigid is RigidBody:
			rigid.apply_impulse(pos3d,
					pos3d.direction_to(rigid.global_transform.origin) * 6)
	
func _input(event):
	if Input.is_action_just_pressed("ui_accept"):
		$Tom.visible = false
		create_rigids()
		explode()
